import Immutable from 'immutable';

import { IState, IAction, ACTION_TYPE, ITodo } from '../../components/TodoList/typings'

const defaultState = Immutable.fromJS({
  todoList: []
})

function todoReducer(state: any = defaultState, action: IAction): IState {
  const { type, payload } = action;
  switch(type) {
    case ACTION_TYPE.INIT_TODOLIST: 
      // return {
      //   ...state,
      //   todoList: payload as ITodo[]
      // };
      return state.set('todoList', [payload]);
    case ACTION_TYPE.ADD_TODO:
      // return {
      //   ...state.todoList,
      //   todoList: [...state.todoList, payload as ITodo]
      // }
      return state.set('todoList', state.get('todoList').push(payload));
    case ACTION_TYPE.REMOVE_TODO:
      // return {
      //   ...state.todoList,
      //   todoList: state.todoList.filter(todo => todo.id !== payload)
      // }
      return state.set('todoList', state.get('todoList').filter((todo: ITodo) => todo.id !== payload));
    case ACTION_TYPE.TOGGLE_TODO:
      // return {
      //   ...state.todoList,
      //   todoList: state.todoList.map((todo: ITodo) => {
      //     return todo.id === payload ? 
      //     {
      //       ...todo,
      //       completed: !todo.completed
      //     } : {...todo}
      //   })
      // }
      return state.set('todoList', state.get('todoList').map((todo: ITodo) => {
          return todo.id === payload ? 
          {
            ...todo,
            completed: !todo.completed
          } : {...todo}
        }));
    default: return state;
  }
}

export default todoReducer;
